package com.cdut.controller;

import com.cdut.pojo.User;
import com.cdut.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("user")
@Api
@CrossOrigin("*")
@Slf4j
public class UserController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    UserService userService;

    /**
     * 添加用户的数据
     * @param user 用户对象
     * @return 状态码
     */
    @PostMapping("adduser")
    @ApiOperation("添加用户")
    @ResponseBody
    public int UserAdd(User user)
    {
        int code=userService.UserAdd(user).getCode();
        return code;
    }


    /**
     * 删除用户的数据
     * @param uid 用户id
     * @return 状态码
     */
    @GetMapping("deleteuser")
    @ApiOperation("删除用户通过id")
    public int DeleteUser(int uid)
    {
        int code=userService.UserDeleteByuid(uid).getCode();
        return code;
    }

    /**
     * 查询全部的用户
     * @param
     * @return List<User>
     */
    @ResponseBody
    @GetMapping("serchalluser")
    @ApiOperation("查询全部用户")
    public List<User> Serch()
    {
        List<User> userList=userService.UserSerch().getData();
        return userList;
    }

    /**
     * 通过邮箱查询用户
     * @param mail 用户邮箱
     * @return User对象
     */
    @ResponseBody
    @GetMapping("serchuserbymail")
    @ApiOperation("通过邮箱查询用户")
    public User SerchBymail(String mail)
    {
        User user=userService.UserSerchBymail(mail).getData();
        return user;
    }

    /**
     * 更新用户的信息
     * @param user 用户里面的id
     * @return 状态码
     */
    @GetMapping("updatauser")
    @ApiOperation("更新用户信息")
    public int UpdataUser(User user)
    {
        int code=userService.UserModifyByid(user).getCode();
        return code;
    }
    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return 视图跳转
     */
    @PostMapping("loginuser")
    @ApiOperation("用户登录")
    public String UserLogin(String username, String password, Model model, boolean remember, HttpServletRequest httpServletRequest)
    {

        try {
            logger.info("正在验证");
            UsernamePasswordToken token = new UsernamePasswordToken(username, password,remember);
            logger.info("[login]remember:"+remember);

            //获取主题对象
            Subject subject = SecurityUtils.getSubject();
            logger.info("[token]"+token);
            subject.login(token);
            //boolean remembered = subject.isRemembered();
            logger.info(username+"登录成功");
            logger.info("[subject]"+subject.getPrincipal());

            return "redirect:../home";
        }catch(UnknownAccountException e) {
            model.addAttribute("loginMsg","用户名或密码错误");
            logger.error("用户名错误");
        }catch (IncorrectCredentialsException e){
            model.addAttribute("loginMsg","用户名或密码错误");
            logger.info("密码错误");
        }
        return "login";

    }



    /**
     * 用户登出
     * @return 首页
     */
    @GetMapping("logout")
    @ApiOperation("用户登出")
    public String Logout(Model model, HttpServletResponse response){
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            Session session = subject.getSession();
            logger.info("用户准备登出");
            session.removeAttribute("loginUser");
            logger.info("已经登出");
            model.addAttribute("logoutMsg","已登出");

            //删除cookie
            Cookie cookie = new Cookie("rememberMe", null);
            cookie.setMaxAge(0);
            response.addCookie(cookie);

            return "redirect:../home";
        }catch (Exception e){
            e.printStackTrace();
            logger.error("未登录不能注销");
            model.addAttribute("logoutMsg","错误:未登录,不能注销");
            return "redirect:../home";
        }
    }

    /**
     * 用户注册
     * @param user 用户
     * @param verificationCode 验证码
     * @param model model
     * @return 状态
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    @ResponseBody
    public String Register(User user, @NonNull int verificationCode, Model model){
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        logger.info("[register]注册验证中=>"+user);

        //如果验证码不正确
        if ((int)session.getAttribute("vcode")!=verificationCode){
            model.addAttribute("regMsg","验证码错误");
            logger.info("验证码错误");
            return 0+"";
        }else {

            //如果验证码和用户名都不重复
            if (userService.UserSerchBymail(user.getMail()).getData()==null&&
                    userService.queryUserByName(user.getUsername()).getData()==null&&
                    Objects.equals((String) session.getAttribute("regName"), user.getUsername())&&
                    Objects.equals((String) session.getAttribute("regMail"), user.getMail())){

                session.removeAttribute("regName");
                session.removeAttribute("regMail");
                //注册用户
                int code = userService.UserAdd(user).getCode();
                session.removeAttribute("vcode");
                return code+"";
            }else{
                if (userService.UserSerchBymail(user.getMail()).getData()!=null){
                    User rejectUser = userService.UserSerchBymail(user.getMail()).getData();
                    logger.info("[register]邮箱重复"+rejectUser);
                }else if (userService.queryUserByName(user.getUsername()).getData()!=null){
                    logger.info("[register]用户名重复");
                }else if (!Objects.equals((String) session.getAttribute("regName"), user.getUsername()) && !Objects.equals((String) session.getAttribute("regMail"), user.getMail())){
                    logger.info("[register]regName"+"=>"+session.getAttribute("regName"));
                    logger.info("[register]regMail"+"=>"+session.getAttribute("regMail"));
                    logger.info("[register]username=>"+user.getUsername());
                    logger.info("[register]usermail=>"+user.getMail());

                    logger.info("[register]提交的用户名和用户邮箱和发送验证邮箱的用户不一致");
                }
                return 0+"";
            }

        }

    }


}
